package com.itcam.interview.pro00.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class FairLockAndUnfairLock {

    public static void main(String[] args) {
        ReentrantLock fairLock = new ReentrantLock(true);
        ReentrantLock unfairLock = new ReentrantLock(false);

        Thread thread1 = new Thread(() -> {
            useLock(fairLock, "Thread1 (fair)");
        });

        Thread thread2 = new Thread(() -> {
            useLock(fairLock, "Thread2 （fair）");
        });

        Thread thread3 = new Thread(() -> {
            useLock(unfairLock, "Thread3 （unfair）");
        });

        Thread thread4 = new Thread(() -> {
            useLock(unfairLock, "Thread4 （unfair）");
        });

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }

    private static void useLock(ReentrantLock lock, String threadName) {
        for (int i = 0; i < 3; i++) {
            lock.lock();
            System.out.println(threadName + " is using the lock. Count: " + i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }
}
